# cython: language_level=3
# -*- coding: utf-8 -*-

import os

try:
    import configparser
except:
    import ConfigParser as configparser

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

def decorator(cls):
    # @wraps(cls)
    class WrapConf:

        def __init__(self, *args, **kwargs):
            self.wrapconf = cls(*args, **kwargs);

        def __getattr__(self, attr):
            return getattr(self.wrapconf, attr);

        def getConfItems(self, sections):
            """ 以字典的形式返回配置文件中的相应section下的配置, 配置中的多个以逗号分隔的值将会转换为字典 """
            config_dict = dict(self.items(sections));
            for key, val in config_dict.items():
                if "," in val:
                    config_dict[key] = val.replace(" ", "").split(",")
            return config_dict

    return WrapConf


@decorator
class CONF(configparser.ConfigParser):
    """
    封装configparser主要是因为2与3中存在大小写问题
    和解析配置文件在本地和生产环境上的差异
    """

    def __init__(self):
        self.config_file = self.generateConFileName()
        self.conf = configparser.ConfigParser()
        try:
            self.conf.read(self.config_file, encoding="utf-8")
        except Exception as e:
            self.conf.read(self.config_file)

    @staticmethod
    def generateConFileName():
        if os.path.isfile(os.path.join(BASE_DIR, "settings-public.ini")):
            return os.path.join(BASE_DIR, "settings-public.ini")
        else:
            if os.path.isfile(os.path.join(BASE_DIR, "settings-dev.ini")):
                return os.path.join(BASE_DIR, "settings-dev.ini")
            else:
                return os.path.join(BASE_DIR, "settings.ini")

    def sections(self):
        return self.conf.sections()

    def options(self, key):
        return self.conf.options(key)

    def items(self, key):
        return self.conf.items(key)

    def get(self, key, name):
        return self.conf.get(key, name).strip()

    def getint(self, key, name):
        return self.conf.getint(key, name)

    def getfloat(self, key, name):
        return self.conf.getfloat(key, name)

    def getboolean(self, key, name):
        return self.conf.getboolean(key, name)


if __name__ == '__main__':
    conf = CONF()
    print(conf.get("mysql_config", "passwd"))